#include <ctime>
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>
#include "RingQueue.hpp"
#include "Task.hpp"

struct ThreadData
{
    RingQueue<Task> *rq;
    std::string threadname;
};

void *Productor(void *args)
{
    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    ThreadData *td = static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name = td->threadname;
    int len = opers.size();
    while (true)
    {
        int data1 = rand() % 10 + 1;
        usleep(10);
        int data2 = rand() % 10;
        char op = opers[rand()%len];
        Task t(data1,data2,op);
        rq->push(t);
        // std::cout<<"Productor : data = "<< data << " name = " << name << std::endl;
        std::cout<<"Productor : Task = "<< t.GetTask() << " who "<< name << std::endl;
        sleep(1);
    }
    
    return nullptr;
}

void *Consumer(void *args)
{
    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    ThreadData *td = static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name = td->threadname;
    while (true)
    {
        // int data = 0;
        // usleep(10);
        Task t;
        rq->pop(&t);
        //处理数据
        t();
        // std::cout<<"Consumer : data = "<< data <<" name = "<< name << std::endl;
        std::cout << "Consumer : Task = " << t.GetTask() << " who: " << name << " result: " << t.Getresult() << std::endl;
        // sleep(1);
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr));
    RingQueue<Task> *rq = new RingQueue<Task>();
    pthread_t c[5], p[3];
    for(int i = 0;i<1;i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Productor-" + std::to_string(i);

        pthread_create(p+i, nullptr, Productor, td);
        usleep(10);

    }
    sleep(1);
    for(int i = 0;i<1;i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Consumer-" + std::to_string(i);

        pthread_create(c+i, nullptr, Consumer, td);
        usleep(10);
    }
    for(int i = 0;i<1;i++)
    {
        pthread_join(p[i], nullptr);
    }
    for(int i = 0;i<1;i++)
    {
        pthread_join(c[i], nullptr);
    }
    return 0;
}